<?php

namespace app\live\controller;

use app\common\model\live\GoodsModel;
use app\common\model\live\AskModel;
use app\common\model\live\GiftModel;
use app\common\model\live\MallModel;
use app\common\model\live\OnlineModel;
use app\common\model\live\RoomModel;
use app\common\model\live\RoomNoticeModel;
use app\common\model\live\RoomTabModel;
use app\common\model\MemberModel;
use think\facade\Cookie;
use wechat\Factory;

class PlayController extends BaseController
{

  private $roomModel;
  private $roomLogin;
  private $wechat;
  private $memberModel;


  /**
   * 初始化
   * @throws \Exception
   */
  public function __construct()
  {
    parent::__construct();

    $this->roomModel   = new RoomModel();
    $this->wechat      = Factory::officialAccount();
    $this->memberModel = new MemberModel();
    $this->roomLogin   = $this->getMemberLogin();
  }

  /**
   * 用户登录
   * @throws \Exception
   */
  public function login()
  {
    $redirect = $this->request->param('redirect',null,'');
    if (!$this->request->has('code')) {
      $this->wechat->oauth
          ->scopes(['snsapi_userinfo'])
          ->redirect($this->request->url(true))
          ->send();
    } else {
      $user = $this->wechat->oauth->user()->getOriginal();
      //注册用户
      $userId = $this->memberModel->add([
          'nick' => $user['nickname'],
          'avatar' => $user['headimgurl'],
          'unionid' => $user['unionid'] ?? '',
          'openid' => $user['openid'],
      ]);
      Cookie::set('member_login', $this->memberModel->setToken($userId));
      $this->redirect(urldecode($redirect));
    }
  }

  /**
   * 播放端首页
   * @return string
   * @throws \Exception
   */
  public function index()
  {
    $roomId = $this->request->param('room_id/d');
    if ($this->checkMemberLogin() === false) $this->redirect('login', ['redirect' => urlencode($this->request->url(true))]);
    //$this->roomLogin = ['userId'=>'1000001']; //本地测试
    /*获取是否在黑名单，如果在黑名单就跳转*/
    $onlineModel = new OnlineModel();
    $userInfo = $onlineModel->getInfo($roomId,$this->roomLogin['userId']);
    if(!empty($userInfo) && isset($userInfo['is_black']) && $userInfo['is_black']==1)  $this->redirect('black',['room_id' => $roomId]);
    $trtcConfig = config('cloud.tencent.trtc');
    /*房间播放地址*/
    $roomInfo            = $this->roomModel->where('room_id', $roomId)->find();
    $roomInfo['content'] = html_out($roomInfo['content']);
    $mallInfo = MallModel::where('room_id',$roomId)->find();
    $playUrl             = $this->roomModel->getPlayUrl($roomId, $roomInfo['host_name']);
    $bannerList          = json_decode($roomInfo['banner'], true);
    $tabList             = RoomTabModel::where('room_id', $roomId)->limit(2)->order('show_order asc')->select();
    foreach ($tabList as $k => $v) {
      $tabList[$k]['tab_content'] = html_out($v['tab_content']);
    }
    //会议通会员是否VIP
    $isVip = 0;
    if($this->request->has('is_vip') && $this->request->param('is_vip/d')==1){
      $timestamp = $this->request->param('timestamp');
      $token = $this->request->param('token');
      if(md5(config('wechat.official_account.app_id').$timestamp)==$token){
        $isVip = 1;
      }
    }
    /***/
    $rewardMoney                      = [
        ['money' => '0.99', 'money_desc' => '想再看你久一些'], 
        //['money' => '0.01', 'money_desc' => '想再看你久一些'],
        ['money' => '2.58', 'money_desc' => '要不要给我一点爱'],
        ['money' => '5.20', 'money_desc' => '撒浪嘿呦，欧巴'],
        ['money' => '8.88', 'money_desc' => '发发发，一路发'],
        ['money' => '13.14', 'money_desc' => '一生一世，一辈子'],
        ['money' => '22.22', 'money_desc' => '祝你早日脱单'],
        ['money' => '66.66', 'money_desc' => '牛牛牛牛 就是牛'],
        ['money' => '88.88', 'money_desc' => '一路发，么么哒'],
        ['money' => '99.99', 'money_desc' => '长长久久，久到离谱'],
    ];
    $giftList                         = GiftModel::where('is_svga',0)->order('show_order asc')->select()->toArray();
    $giftList2                         = GiftModel::where('is_svga',1)->order('show_order asc')->select()->toArray();
    $memberInfo                       = MemberModel::where('id', $this->roomLogin['userId'])->find();
    $this->roomLogin['name']          = $memberInfo['name'];
    $this->roomLogin['contact_phone'] = $memberInfo['contact_phone'];
    $this->roomLogin['company_name']  = $memberInfo['company_name'];
    $notice                           = RoomNoticeModel::where("room_id", $roomId)->order('id', 'desc')->find();
    $shareUrl                         = empty($roomInfo['room_share']) ? $this->request->domain() . $this->request->url() : html_out($roomInfo['room_share']);
    $shareImgtext                     = empty($roomInfo['share_img_text']) ? [] : explode("\r\n", $roomInfo['share_img_text']);
    //微信分享
    $wxJsApi = $this->wechat->jssdk->buildConfig(['hideAllNonBaseMenuItem','editAddress']);
    $this->assign('is_vip', $isVip);
    $this->assign('wx_js_api', $wxJsApi);
    $this->assign('notice', $notice);
    $this->assign('gift_list', array_chunk($giftList, 8));
    $this->assign('gift_list2', array_chunk($giftList2, 8));
    $this->assign('reward_money', $rewardMoney);
    $this->assign('play_url', $playUrl);
    $this->assign('trtc_config', $trtcConfig);
    $this->assign('room_info', $roomInfo);
    $this->assign('mall_info', $mallInfo);
    $this->assign('banner_list', $bannerList);
    $this->assign('tab_list', $tabList);
    $this->assign('room_login', $this->roomLogin);
    $this->assign('share_url', $shareUrl);
    $this->assign('share_img_text', $shareImgtext);
    if (time() > $roomInfo['room_time']) {
      $tpl = $roomInfo['room_status'] == 2 ? 'live_end' : 'index';
    } else {
      $tpl = 'live_wait';
    }
    //if($roomId=='881138403') $tpl='index_test';
    //$memberLogin = $this->getMemberLogin();
    return $this->fetch($tpl);
  }
  /*黑名单页面*/
  public function black(){
    return $this->fetch();
  }

  /**
   * 加入房间记录用户
   * @throws \Exception
   */
  public function join()
  {
    $roomId = $this->request->param('room_id/d');
    if ($this->checkMemberLogin() === false) $this->redirect('login', ['room_id' => $roomId]);
    $onlineModel = new OnlineModel();
    $data        = $this->request->param();
    $this->validate($data, [
        'room_id|房间号' => 'number',
        'userId|用户Id' => 'require'
    ]);
    $onlineModel->add([
        'room_id' => $data['room_id'],
        'user_id' => $data['userId'],
        'nick' => $data['nick'],
        'avatar' => $data['avatar'],
        'is_vip' => $data['is_vip'],
        'role' => 'audience',
    ]);
    $this->success('操作成功');
  }

  /**
   * 提交问答，存库后发送群消息
   * @throws \Exception
   */
  public function addAsk()
  {
    $roomId = $this->request->param('room_id/d');
    if ($this->checkMemberLogin() === false) $this->redirect('login', ['room_id' => $roomId]);
    $data = $this->request->param();
    $this->validate($data, [
        'ask_content|咨询内容' => 'require',
        'room_id|直播间' => 'require',
        'member_id|提问人' => 'require|float|>:0',
    ]);
    /*
    if (isset($data['name'])) {
      $memberModel = new MemberModel();
      $memberModel->where('id', $data['member_id'])->update([
          'name' => $data['name'],
          'contact_phone' => $data['contact_phone'],
          'company_name' => $data['company_name']
      ]);
    }
    */
    $askModel = new AskModel();
    $askModel->add($data);
    $this->success('提交成功');
  }

  /**
   * 获取问答列表
   * @return array
   * @throws \Exception
   */
  public function getAsklist()
  {
    $roomId = $this->request->param('room_id/d');
    if ($this->checkMemberLogin() === false) $this->redirect('login', ['room_id' => $roomId]);
    $askModel = new AskModel();
    $list     = $askModel->where('room_id', $roomId)->where('member_id', $this->roomLogin['userId'])->order('status asc,create_time desc')->select();
    $list     = $list->isEmpty() ? [] : $askModel->_formatList($list);
    $todoNum  = $askModel->where('room_id', $roomId)->where('status', 0)->count();
    return ['list' => $list, 'todo_num' => $todoNum, 'total' => count($list)];
  }


  /**
   * 获取点赞列表
   * @throws \Exception
   */
  public function zan()
  {
    $roomId = $this->request->param('room_id/d');
    if ($this->checkMemberLogin() === false) $this->redirect('login', ['room_id' => $roomId]);
    $num   = $this->request->param('num/d', 1);
    $total = D('live.Zan')->changeNum($roomId, $num);
    $this->success('操作成功', null, $total);
  }

  /**
   * 获取在线用户
   * @throws \Exception
   */
  public function total()
  {
    $roomId = $this->request->param('room_id/d');
    if ($this->checkMemberLogin() === false) $this->redirect('login', ['room_id' => $roomId]);
    $num = $this->request->param('num/d',0);
    if($num==0){
      $time = time(); //当前时间
      $beginTime = $this->request->param('begin_time'); //开播时间
      $appointHour = $this->request->param('appoint_hour'); //30分钟
      $appointNum = $this->request->param('appoint_num'); //5000人
      $sec = (ceil($appointNum/($appointHour*60))); //每秒增加人数
      $randNum = rand(0,$sec+8);
      $diff = (int)($time-$beginTime);
      if($diff<($appointHour*60)){
        D('live.Online')->getInterface()->set("{$roomId}:member_total",$diff*$sec+$randNum);
      }
      $total = D('live.Online')->getInterface()->get("{$roomId}:member_total");
    }else{
      $total = D('live.Online')->memberOnline($roomId,$num);
    }
    $this->success('ok', null, (int)$total);
  }

  /**
   * 获取红包信息
   * @throws \Exception
   */
  public function hongbao()
  {
    $param            = $this->request->param();
    $data['option']   = html_out($param['option']);
    $data['type']     = $param['type'];
    $data['msg_time'] = time();
    D('live.Chat')->chat($param['room_id'], $data);
	
	
	  $chat['option']   = html_out($param['option']);
    $chat['type']     = $param['type'];
    $chat['msg_time'] = time();
    $chat['userdata'] = $param['userdata'];
    D('live.Chat')->dashang($param['room_id'], $chat);
	
    $this->success('操作成功');
  }

  /*获取商品列表*/
  public function getGoodsList(){
    $roomId = $this->request->param('room_id');
    $goodsModel = new GoodsModel();
    $query = [];
    $query[] = ['room_id','=',$roomId];
    $query[] = ['is_sale','>=',0];
    $list = $this->getList('live.Goods',[],['order'=>'is_current desc,is_sale desc,show_order asc'],$query);
    if(empty($list)) abort(500,'直播间还没有上架商品');
    $currentInfo = $goodsModel->where($query)->where('is_current',1)->find();
    $data['list'] = $list;
    $data['current'] = $currentInfo;
    $this->success('获取成功','',$data);
  }
}